package net.loyintean.pearlshell.validation.rule;

import net.loyintean.pearlshell.validation.IValidRule;
import net.loyintean.pearlshell.validation.IValidRuleConfig;

/**
 * 将待校验数据当做String来处理
 * <p>
 * 并且，处理掉null和"NULL"/"null"，将它们都处理为空字符串。
 * 
 * @author：jun.lin@yeepay.com
 * @since：2015年1月2日 下午11:11:21
 * @version:
 */
public abstract class AbstractStringValidRuleImpl implements IValidRule {

	/** NULL：null */
	private static final String NULL = "null";

	/**
	 * valid the toValid as a string. <br>
	 * 把toValid当做字符串来进行校验
	 * <p>
	 * if it's null, this method will deal with it as an empty String.<br>
	 * 如果toValid是null，这个方法将会把它处理为空字符串。
	 * <p>
	 * the valid is depends on {@link #validString(String, IValidRuleConfig)}.<br>
	 * 实际的校验逻辑依赖于 {@link #validString(String, IValidRuleConfig)}
	 * <p>
	 * 2015-01-02 jun.lin 增加一个限制：将字符串"null"和"NULL"作为null来处理
	 * 
	 * @author Loy
	 * @see net.loyintean.pearlshell.validation.IValidRule#valid(java.lang.Object,
	 *      net.loyintean.pearlshell.validation.IValidRuleConfig)
	 * @see #validString(String, IValidRuleConfig)
	 */
	@Override
	public final boolean valid(Object toValid, IValidRuleConfig config) {

		String validStr = null;
		if (toValid != null) {

			assert toValid instanceof String;

			validStr = (String) toValid;

			// [start] jun.lin 处理字符串"null" 2015-01-02
			if (NULL.equals(validStr.toLowerCase())) {
				validStr = "";
			}
			// [end] jun.lin 处理字符串"null" 2015-01-02

		} else {
			validStr = "";
		}

		return validString(validStr, config);
	}

	protected abstract boolean validString(String toValid,
			IValidRuleConfig config);
}
